<!--
 * @Author: sunboylu 1044768335@qq.com
 * @Date: 2023-12-10 17:30:35
 * @LastEditors: sunboylu 1044768335@qq.com
 * @LastEditTime: 2023-12-11 10:25:16
 * @FilePath: /gitee/html-demo/switch.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html>

<head>
  <title>WebRTC Camera Switch</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      font-family: Arial, sans-serif;
      background-color: #f2f2f2;
    }

    .container {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 1em;
      box-sizing: border-box;
    }

    #video {
      width: 100%;
      max-width: 500px;
      height: auto;
      border: 1px solid #ccc;
      border-radius: 5px;
    }

    .switch {
      margin-top: 20px;
      padding: 10px 20px;
      font-size: 2em;
      /* Increase font size for better readability */
      color: #fff;
      background-color: #007BFF;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="container">
    <video id="video" autoplay></video>
    <button id="switch" class="switch">Switch Camera</button>
  </div>
  <script src="https://cdn.bootcss.com/vConsole/3.2.0/vconsole.min.js"></script>
  <script>
      // 初始化
  var vConsole = new VConsole();
  console.log('Hello world');
  let videoElement = document.getElementById("video");
let currentStream;
let currentDeviceId = 0;
let videoDevices = [];
// 请求摄像头权限
function requestCameraPermission() {
 navigator.mediaDevices.getUserMedia({
  audio: true,
  video: {
    width: { min: 1280 },
    height: { min: 720 },
  },
}).then((stream)=>{
  stopStream(stream)
});
}
requestCameraPermission()
// 开始获取权限并处理权限状态


    // 获取所有设备信息
    function getDevices() {
      return navigator.mediaDevices.enumerateDevices();
    }

    // 获取摄像头信息
    function getVideoDevices(deviceInfos) {
      let videoDevices = [null, null]; // 默认前后摄像头都为空
      let videoDeviceIndex = 0;
      for (let i = 0; i !== deviceInfos.length; ++i) {
        let deviceInfo = deviceInfos[i];
        if (deviceInfo.kind === 'videoinput') {
          videoDevices[videoDeviceIndex] = deviceInfo.deviceId;
          videoDeviceIndex++;
        }
      }
      return videoDevices;
    }

    // 开启摄像头
    function startStream(deviceId) {
      if (typeof currentStream !== 'undefined') {
        stopStream(currentStream);
      }
setTimeout(()=>{
  let constraints = {
      audio:true,
        video: {
          deviceId: {
            exact: deviceId
          }
        }
      };
      navigator.mediaDevices.getUserMedia(constraints).then(stream => {
        currentStream = stream;
        videoElement.srcObject = stream;
      }).catch(error => {
        navigator.mediaDevices.getUserMedia(constraints).then(stream => {
        currentStream = stream;
        videoElement.srcObject = stream;
      })
        console.log('Error: ', error);
      });
},3000)
    }

    // 关闭摄像头
    function stopStream(stream) {
      let tracks = stream.getTracks();
      tracks.forEach(track => {
        track.stop();
      });
    }

    // 切换摄像头
    function switchCamera() {
      getDevices().then(deviceInfos => {
        let videoDevices = getVideoDevices(deviceInfos);
        if (videoElement.srcObject === null) {
          currentDeviceId =0
          startStream(videoDevices[currentDeviceId]);
        } else {
          if (currentDeviceId===0) {
            currentDeviceId =1
            startStream(videoDevices[currentDeviceId]);
          } else {
            currentDeviceId =0
            startStream(videoDevices[currentDeviceId]);
          }
        }
      });
    }

    // 绑定切换摄像头事件
    document.getElementById('switch').addEventListener('click', switchCamera);

  </script>
</body>

</html>